package com.pwt.controller.permission;

import com.pwt.annotation.Update;
import com.pwt.common.CustomException;
import com.pwt.common.DataNotFoundException;
import com.pwt.common.ResultPage;
import com.pwt.entity.User;
import com.pwt.model.UserGrantsModel;
import com.pwt.model.UserPOJO;
import com.pwt.security.utils.JWTUser;
import com.pwt.security.utils.JWTUtils;
import com.pwt.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name = "用户相关功能")
public class UserController {

    @Autowired
    UserService userService;


    @PostMapping("users")
    @Operation(description = "新增用户",summary = "新增用户")
//    @PreAuthorize("hasRole('root')")
    public User add(@RequestBody @Validated User user) throws CustomException {
        return userService.add(user);
    }

    @GetMapping("users")
    @Operation(description = "查询用户",summary = "查询用户")
//    @PreAuthorize("hasAnyAuthority('permission::user::view')")
    public ResultPage<UserPOJO> list(@Parameter(description = "容量",required = true) @RequestParam Integer limit,
                                    @Parameter(description = "页码",required = true) @RequestParam Integer page,
                                    @Parameter(description = "用户名") @RequestParam(required = false) String username,
                                    @Parameter(description = "昵称") @RequestParam(required = false) String nickName) throws CustomException {
        return userService.list(limit,page,username,nickName);
    }

    @GetMapping("users/{id}")
    @Operation(description = "查询用户",summary="查询用户")
    public UserPOJO user(@Parameter(description = "用户ID",required = true) @PathVariable String id) throws DataNotFoundException {
        return userService.user(id);
    }

    @PutMapping("users")
    @Operation(description = "修改用户",summary = "修改用户")
    public User edit(@RequestBody @Validated(value = Update.class) User user) throws CustomException {
        return userService.edit(user);
    }


    @DeleteMapping("users/{id}")
    @Operation(description = "删除用户",summary = "删除用户")
    public String delete(@Parameter(description = "用户ID",required = true) @PathVariable String id) {
        return userService.delete(id);
    }

    @PostMapping("users/grants")
    @Operation(description = "用户授权",summary = "用户授权")
    public void grants(@RequestBody @Validated UserGrantsModel userGrantsModel) {
        userService.grants(userGrantsModel);
    }
}
